package com.ovopark.firecar.okhttp;

import android.text.TextUtils;

import com.socks.library.KLog;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit Service服务生成者
 */
public class RsGenerator {
    public static final String TAG = "RsGenerator";
    /**
     * 基础数据url.
     */
    private static String mBase;
    private static Retrofit sRetrofit;

    public static void createNewRetrofit(String baseUrl, Interceptor interceptor) throws IllegalArgumentException{
        KLog.i(TAG,"createNewRetrofit base url: "+baseUrl);
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            if (!TextUtils.isEmpty(baseUrl)) {
                mBase = baseUrl;
            }

        //时间超时拦截器.
        TimeOutInterceptor timeOutInterceptor = new TimeOutInterceptor();

            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .addInterceptor(httpLoggingInterceptor)
                    .addInterceptor(timeOutInterceptor)
                    .addInterceptor(interceptor)
                    .connectTimeout(30L, TimeUnit.SECONDS)
                    .readTimeout(1L, TimeUnit.MINUTES)
                    .writeTimeout(1L, TimeUnit.MINUTES)
//                .addInterceptor(new FakeInterceptor())
                    .build();
            sRetrofit = new Retrofit.Builder()
                    .baseUrl(mBase)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(JsonConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient)
                    .build();
    }

    public static Retrofit getInstance() {
        return sRetrofit;
    }

    public static <S> S create(Class<S> serviceClass) {
        return sRetrofit.create(serviceClass);
    }
}
